package com.dy.course.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dy.course.common.BaseException;
import com.dy.course.common.BaseService;
import com.dy.course.common.Constant;
import com.dy.course.entity.RoomBean;
import com.dy.course.mapper.RoomMapper;
import com.dy.course.model.Room;
import com.dy.course.service.IRoomService;

import tk.mybatis.mapper.entity.Example;

@Service
public class RoomService extends BaseService<Room> implements IRoomService{
	
	@Autowired
	private RoomMapper roomMapper;

	@Override
	public List<Room> query(RoomBean rb) {
		logger.info("【查询教室/会议室服务】,参数:rb=" + JSON.toJSONString(rb));
		super.startPage(rb);
		Room c = new Room();
		BeanUtils.copyProperties(rb, c);
		return getMapper().select(c);
	}
	
	/**
	 * 创建教室会议室
	 */
	@Override
	public Long insert(RoomBean rb) {
		logger.info("【创建教室/会议室服务】,参数:rb=" + JSON.toJSONString(rb));
		Example example = new Example(Room.class);
		example.createCriteria().andEqualTo("name",rb.getName()).andEqualTo("universityId",rb.getUniversityId()).andEqualTo("mck",rb.getMck());
		int count = getMapper().selectCountByExample(example);
		if(count > 0){
			logger.info("该教室/会议室已存在rb=" + JSON.toJSONString(rb));
			throw new BaseException(Constant.Code.ROOM_EXISTS,"该教室/会议室已存在",null);
		}
		Room mr = new Room();
		BeanUtils.copyProperties(rb, mr);
		getMapper().insertSelective(mr);
		return mr.getId();
	}

	/**
	 * 删除教室会议室
	 */
	@Override
	public void delet(RoomBean ci) {
		logger.info("【删除教室/会议室服务】,参数:id=" + JSON.toJSONString(ci.getId()));
		Room room = roomMapper.selectByPrimaryKey(ci.getId());
		if(room == null){
			logger.error("【】数据库异常,数据已经被删除或者不存在,id={}",ci.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
		Example example = new Example(Room.class);
		example.createCriteria().andEqualTo("id",ci.getId());
		int count = roomMapper.deleteByExample(example);
		if(count <= 0){
			logger.error("【】数据库异常,数据已经被删除或者不存在,id={}",ci.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
	}

	/**
	 * 修改教室会议室
	 */
	@Override
	public void update(RoomBean rb) {
		logger.info("【修改教室/会议室服务】,参数:rb=" + JSON.toJSONString(rb));
		Room room = roomMapper.selectByPrimaryKey(rb.getId());
		if(room == null){
			logger.error("【】数据库异常,数据已经被删除或者不存在,id={}",rb.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
		
		BeanUtils.copyProperties(rb, room);
		int count = roomMapper.updateByPrimaryKey(room);
		if(count < 1){
			logger.error("【】数据库异常,数据修改失败,mb=",JSON.toJSONString(room));
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据修改失败", null);
		}
	}
}
